<template>
  <div class="app-container">
    <div class="top-header">
      <div class="tabs">
        <div class="tab-item" :class="{active:activeTopHeaderTab===0}" @click="onTabClick('activeTopHeaderTab',0)">页面装修</div>
        <div class="tab-item" :class="{active:activeTopHeaderTab===1}" @click="onTabClick('activeTopHeaderTab',1)">模板库</div>
      </div>
      <div class="toolbar">
        <el-button type="text" size="mini" @click="addPageTemplate">保存为新模板</el-button>
        <el-button type="primary" size="mini" @click="onSaveTemplate">保存</el-button>
      </div>
    </div>
    <div class="content">
      <div v-show="activeTopHeaderTab===0" class="edit-area">
        <div class="left-area">
          <div class="left-area-header">基础模块</div>
          <div class="left-area-content">
            <div v-for="m in modules" :key="m.id" class="item" @mouseover.self="$event=>onMouseoverModuleItem($event,m)" @mouseleave.self="$event=>onMouseleaveModuleItem($event,m)" @click="onClickModuleItem(m)">
              <div class="bg-icon" :style="{backgroundPosition:m.style.backgroundPosition}" />
              <div class="title">
                {{ m.title }}
              </div>
            </div>
          </div>
        </div>
        <div class="middle-area" @click.self="onClickMiddleArea">
          <div class="main-view">
            <div class="module-container  header">
              <header-view :options="headerModule.options" />
              <div class="tool-kit">
                <i class="el-icon-edit" @click="onEditModule(headerModule)" />
              </div>
            </div>
            <div class="module-view">
              <div v-for="(m,i) in moduleList" :key="m._uid" class="module-container">
                <component :is="m.id+'View'" :options="m.options" />
                <div class="tool-kit">
                  <i class="el-icon-edit" @click="onEditModule(m)" />
                  <i v-show="i!==0" class="el-icon-top" @click="onMoveModule(i,-1)" />
                  <i v-show="i!==(moduleList.length-1)" class="el-icon-bottom" @click="onMoveModule(i,1)" />
                  <i class="el-icon-close" @click="onDelModule(i)" />
                </div>
              </div>
            </div>
            <div class="module-container  footer">
              <footer-view :options="footerModule.options" />
              <!-- <div class="tool-kit">
                <i class="el-icon-edit" @click="onEditModule(footerModule)" />
              </div> -->
            </div>
          </div>
        </div>
        <div class="right-area">
          <component :is="currentModule.id+'Options'" v-if="currentModule" v-model="currentModule.options" :title="currentModule.title" />
          <div v-else class="main-options">
            <div class="options-header">
              <div class="tabs">
                <div class="tab-item active">页面设置</div>
              </div>
            </div>
            <div class="options-content">
              <el-form :model="pageOptions" label-width="80px" size="mini">
                <div class="page-options">
                  <el-form-item label="模板名称">
                    <el-input v-model="pageOptions.name" />
                  </el-form-item>
                  <!-- <el-form-item label="使用系统默认图片">
                    <el-radio v-model="pageOptions.isUseDefaultPic" :label="true">是</el-radio>
                    <el-radio v-model="pageOptions.isUseDefaultPic" :label="false">否</el-radio>
                  </el-form-item> -->
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </div>
      <div v-show="activeTopHeaderTab===1" style="height: 100%;">
        <div class="template-list">
          <div class="template-item" title="新增模板" @click="onAddTemplate">
            <div class="image" />
          </div>
          <div v-for="template in templateList" :key="template.id" class="template-item">
            <div class="image">
              <div class="mask">
                <el-button v-if="template.status===0" size="mini" type="primary" @click="homeTemplateLaunch(template.id)">使用</el-button>
                <el-button size="mini" type="success" @click="onEditTemplate(template)">编辑</el-button>
                <!-- <el-button size="mini">预览</el-button>
              <el-button size="mini">上传封面</el-button> -->
                <el-button size="mini" @click="onDelTemplate(template.id)">删除</el-button>
              </div>
            </div>
            <div class="text">{{ getTemplateName(template.content) }}</div>
          </div>
        </div>
        <pagination
          :total="pages.total"
          :page.sync="pages.pageNum"
          :limit.sync="pages.pageSize"
          @pagination="getTemplateList"
        />
      </div>
    </div>
  </div>
</template>
<script>
import { components, modules } from './modules'
import { createUniqueString, deepClone } from '@/utils'
import { listPageTemplate, updatePageTemplate, addPageTemplate, delPageTemplate, homeTemplateLaunch } from '@/api/decorate'

export default {
  name: 'ShopDecoration',
  components: {
    ...components
  },
  data() {
    return {
      activeTopHeaderTab: 0,
      templateList: [],
      pages: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      modules: modules.filter(el => el.selectable),
      moduleList: [],
      currentModule: null,
      activeMainOpt: '1',
      pageOptions: null,
      headerModule: null,
      footerModule: null,
      templateId: null
    }
  },
  computed: {
    moduleCountMap() {
      const map = {}
      const { moduleList } = this
      for (let i = 0; i < moduleList.length; i++) {
        const { id } = moduleList[i]
        if (!map[id]) {
          map[id] = 0
        }
        map[id]++
      }
      return map
    },
    templateOptions() {
      const { pageOptions, headerModule, footerModule, moduleList } = this
      return JSON.stringify({ pageOptions, headerModule, footerModule, moduleList })
    }
  },
  created() {
    this.init()
    this.getTemplateList()
  },
  methods: {
    init() {
      this.moduleList = []
      this.headerModule = deepClone(modules[0])
      this.footerModule = deepClone(modules[modules.length - 1])
      this.pageOptions = {
        name: ''
      }
    },
    getTemplateList() {
      const { pageSize, pageNum } = this.pages
      listPageTemplate({ pageNum, pageSize }).then(res => {
        this.pages.total = res.total
        this.templateList = res.rows
      })
    },
    addPageTemplate() {
      addPageTemplate({ content: this.templateOptions }).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.getTemplateList()
      })
    },
    updatePageTemplate() {
      updatePageTemplate({ id: this.templateId, content: this.templateOptions }).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.getTemplateList()
      })
    },
    homeTemplateLaunch(id) {
      homeTemplateLaunch({ id }).then(res => {
        this.$message({
          message: '设置成功',
          type: 'success'
        })
        this.getTemplateList()
      })
    },
    onTabClick(tab, i) {
      this[tab] = i
    },
    onMouseoverModuleItem(e, m) {
      e.target.getElementsByClassName('bg-icon')[0].style.backgroundPosition = m.style.hoverBackgroundPosition
    },
    onMouseleaveModuleItem(e, m) {
      e.target.getElementsByClassName('bg-icon')[0].style.backgroundPosition = m.style.backgroundPosition
    },
    onClickMiddleArea() {
      this.currentModule = null
    },
    onClickModuleItem(m) {
      const { id, limit } = m
      const count = this.moduleCountMap[id] || 0
      if (count >= limit) {
        this.$message({
          message: `该模块只允许添加${limit}个`,
          type: 'warning'
        })
      } else {
        this.moduleList.push({ ...deepClone(m), _uid: `${id}_${createUniqueString()}` })
        this.$message({
          message: '添加成功',
          type: 'success'
        })
      }
    },
    onEditModule(m) {
      this.currentModule = m
    },
    onMoveModule(i, d) {
      const moduleList = [...this.moduleList]
      const current = moduleList[i]
      moduleList[i] = moduleList[i + d]
      moduleList[i + d] = current
      this.moduleList = [].concat(moduleList)
    },
    onDelModule(i) {
      this.moduleList.splice(i, 1)
    },
    onAddTemplate() {
      this.templateId = null
      this.init()
      this.activeTopHeaderTab = 0
    },
    onDelTemplate(id) {
      this.$confirm('确认删除此模板吗?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delPageTemplate(id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getTemplateList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    onSaveTemplate() {
      if (this.templateId) {
        this.updatePageTemplate()
      } else {
        this.addPageTemplate()
      }
    },
    getTemplateName(content) {
      return JSON.parse(content).pageOptions.name
    },
    onEditTemplate(template) {
      this.templateId = template.id
      const { pageOptions, headerModule, footerModule, moduleList } = JSON.parse(template.content)
      this.pageOptions = pageOptions
      this.headerModule = headerModule
      this.footerModule = footerModule
      this.moduleList = moduleList
      this.activeTopHeaderTab = 0
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container{
  height: calc(100vh - 84px);
  padding-top:0;
  padding-bottom: 0;
}
.top-header {
  height: 50px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  justify-content: space-between;
  box-shadow: 2px 2px 10px rgba(0,0,0,.1);
  padding: 0 10px;
}
::v-deep .tabs{
  height: 100%;
  display: flex;
  align-items: center;
  .tab-item{
    padding: 0 6px;
    margin:0 6px;
    height: 100%;
    cursor: pointer;
    line-height: 50px;
  }
  .tab-item.active,.tab-item:hover{
    border-bottom:2px solid #1890ff;
    color:#1890ff
  }
}
.content{
  height: calc(100% - 50px);
  overflow: hidden;
}
.template-list{
  height: calc(100% - 60px);
  overflow: auto;
}
.template-item{
  display: inline-block;
  width: 200px;
  height: 350px;
  margin: 15px 15px 0 0;
  vertical-align: middle;
  .image{
    background-image: url('../../../assets/images/nocover.png');
    background-size: 100%;
    height: 320px;
    overflow: hidden;
  }
  .text{
    margin-top: 10px;
    text-align: center;
    font-size: 14px;
    color: #333;
  }
  .mask{
    width: 100%;
    height: 100%;
    transform: translateY(100%);
    background-color: rgba(0,0,0,.4);
    transition: all .5s;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
  }
  .el-button{
    margin-bottom: 15px;
    width: 95px;
  }
  .el-button + .el-button{
    margin-left: 0;
  }
  .el-button:last-child{
    margin-bottom: 0;
  }
  &:hover .mask{
    transform: translateY(0);
  }
}
.template-item:first-child{
  cursor: pointer;
  display: inline-block;
  text-align: center;
  .image{
    box-shadow: 2px 2px 10px rgba(0,0,0,.1);
    background: url('../../../assets/images/add.png') center center no-repeat;
  }
}
.edit-area{
  display: flex;
  height: 100%;
}
.left-area{
  width: 200px;
  height: 100%;
  overflow: auto;
  border-left: 1px solid #f2f2f2;
}
.left-area-header{
  height: 50px;
  line-height: 50px;
  padding: 0 20px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #f2f2f2;
  font-weight: bold;
}
.left-area-content{
  display: flex;
  flex-wrap: wrap;
  .item{
    width: 50%;
    height: 100px;
    font-size: 12px;
    text-align: center;
    color: #333;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border-right: 1px solid #f2f2f2;
    border-bottom: 1px solid #f2f2f2;
  }
  .bg-icon{
    width: 30px;
    height: 30px;
    background-image: url('../../../assets//images/icon_spirit.png');
    margin-bottom: 10px;
    transition: all .2s;
  }
  .item:hover{
    color:#26b594;
  }
}
.middle-area{
  flex:1;
  height: 100%;
  overflow: auto;
  background-color: #f0f0f0;
}
.right-area{
  width: 450px;
  height: 100%;
  overflow: auto;
}
::v-deep .options-header{
  height: 50px;
  background-color: #fbfbfb;
  font-size: 14px;
}
::v-deep .el-form{
  padding: 15px;
}
.module-container{
  position: relative;
  .tool-kit{
    position: absolute;
    top:0;
    right:-24px;
    display: none;
    [class^=el-icon-]{
      cursor: pointer;
      width:24px;
      background-color:rgba(0, 0, 0, .7);
      color:#fff;
      height: 24px;
      text-align: center;
      line-height: 24px;
      margin-bottom: 2px;
    }
  }
  &:hover .tool-kit{
    display: flex;
    flex-direction: column;
  }
}
.main-view{
  width: 390px;
  // height: 600px;
  min-height: 600px;
  margin:20px auto 20px;
  box-shadow: 2px 2px 10px rgba(0,0,0,.1);
  border-radius: 8px;
  background-color: #f5f5f5;
  position: relative;
  display: flex;
  flex-direction: column;
}
.module-view{
  // overflow: auto;
  padding-bottom:60px;
}
.module-view::-webkit-scrollbar {
  display: none;
}
.module-container.footer{
  height: 50px;
  background-color: #fff;
  position: absolute;
  bottom: 0;
  width: 100%;
}
</style>
